let express = require('express');
let path = require('path');
let favicon = require('serve-favicon');
let logger = require('morgan');
let cookieParser = require('cookie-parser');
let bodyParser = require('body-parser');

let Token = require('./util/token');

let index = require('./routes/index');
let p = require('./routes/p');
let order = require('./routes/order');
let orderMgt = require('./routes/orderMgt');
let upload = require('./routes/upload');
let by = require('./routes/by');
let video = require('./routes/video');
let webRTC = require('./routes/webRTC');
let aMap = require('./routes/aliMap');
let verificationCode = require('./routes/verificationCode');
let QR_Code = require('./routes/QR_Code');
let temperatureStatistics = require('./routes/temperatureStatistics');
let temp = require('./routes/temp');
let msc = require('./routes/msc51');


// 获取数据


let app = express();


// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

// uncomment after placing your favicon in /public
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json({'limit':'10000kb'}));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// 不进行Authorization认证路径
let whiteList = ['/','/login','/user','/socket', '/send', '/upload/token', '/by/upload', '/by/upload-test', '/video/','/p',
                    '/rtc', '/upload/', '/upload/getToken', '/upload/getImageUrl', '/upload/qiniu', '/aMap/',
                    '/verificationCode/',
                    '/QR_Code/',
                    '/temperatureStatistics/',
                    '/temp/','/temp/update','/temp/getTemp',
                    '/msc'
];

// 访问权限控制
app.all('*',function(req,res,next){
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With,Content-Type,X-Token,Authorization");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",'Express');
    // res.setHeader("Content-Type", "application/json;charset=utf-8");
    if(whiteList.indexOf(req.url.split('?')[0])===-1){
        let Authorization = req.headers['authorization'];
        if(Authorization){
            if(Token.checkToken(Authorization)){
                next()
            } else {
                res.send({
                    code:10001,
                    success: false,
                    data: {},
                    message: '非法Token'
                })
            }
        } else {
            res.send({
                code:10001,
                success: false,
                data: {},
                message: '没有Token'
            })
        }
    } else {
        next()
    }
});

app.use('/', index);
app.use('/by', by);
app.use('/p', p);
app.use('/order', order);
app.use('/orderMgt', orderMgt);
app.use('/upload', upload);
app.use('/video', video);
app.use('/rtc', webRTC);
app.use('/aMap', aMap);
app.use('/verificationCode', verificationCode);
app.use('/QR_Code', QR_Code);
app.use('/temperatureStatistics', temperatureStatistics);
app.use('/temp', temp);
app.use('/msc', msc);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  let err = new Error('Not Found');
  err.status = 404;
  // 返回未定义接口
  res.send({
      message: '未定义接口(Undefined Interface)',
      success: false,
      data: {},
      code: err.status
  })
  // next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
 //  res.status(err.status || 500);
  let message = '';
  if(err.status === 500){
      message = '服务器内部错误(Internal Server Error)'
  } else if(err.status === 400 ){
      message = '错误的请求(Bad Request)'
  } else {
      message = err.message
  }
  // 返回失败接口
  res.send({
      message: message,
      success: false,
      data: {},
      code: err.status || 10004
  })
  // 返回失败页面
  // res.render('error');
});

module.exports = app;
